package org.hitchhike.web.front.controller;

import java.io.File;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hitchhike.common.domain.BaseEntity;
import org.hitchhike.common.utils.WritePhotoUtils;
import org.hitchhike.common.web.controller.BaseController;
import org.hitchhike.core.domain.User;
import org.hitchhike.core.exception.ErrorInfo;
import org.hitchhike.core.service.UserService;
import org.hitchhike.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/front/image")
public class ImageController extends BaseController<BaseEntity, Long> {
  private Logger logger = LoggerFactory.getLogger(getClass());

  @Autowired
  private UserService userService;
  @Autowired
  private FileUtil fileUtil;

  @ResponseBody
  @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
  public ErrorInfo<String> uploadImg(@RequestParam("imgStr") String imgStr) throws Exception {
    ErrorInfo<String> r = new ErrorInfo<>();
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    user.setImage(imgStr.getBytes("UTF-8"));

    try {
      userService.update(user);
      r.setCode(ErrorInfo.OK);
    } catch (Exception e) {
      logger.error(e.getMessage());
      r.setCode(ErrorInfo.ERROR);
    }
    return r;
  }

  @RequestMapping(value = "/showImage/{fileName}", method = RequestMethod.GET)
  public void showImage(final HttpServletRequest request, final HttpServletResponse response,
      @PathVariable String fileName) {
    try {
      String path = fileUtil.getPath();
      if (fileName == null) {

      } else {
        path += fileName.replace("@", ".");
      }
      InputStream in = request.getServletContext().getResourceAsStream(path);
      int length = in.available();
      byte[] data = new byte[length];
      in.read(data);
      in.close();
      WritePhotoUtils.writePhotoData(response, fileUtil.getPrefix(path), data);
    } catch (Exception e) {
    }
  }

  @RequestMapping(value = "/test", method = RequestMethod.GET)
  public void test(HttpServletRequest request) {
    System.out.println(request.getServletContext().getRealPath(File.separator));
    System.out.println(request.getServletContext().getRealPath("/WEB-INF/upload/"));
  }
}
